package web.dao.impl;

import web.dao.IUserDAO;
import web.entity.SUser;
import web.utils.GenerateCode;
import web.utils.JdbcUtils;
import web.utils.MdsUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.List;

public class UserDAOImpl implements IUserDAO {
    @Override
    public List<SUser> showPage(int start, int limit) {
        return JdbcUtils.selectAll(SUser.class,"select * from s_user limit ?,?",start,limit);

    }

    @Override
    public int selectCount() {
        int i = JdbcUtils.pageCount("select count(*) from s_user");
        return i;
    }

    @Override
    public String getYzm(ServletRequest req, ServletResponse res) {
        String yzmValue=null;
        try {
            ServletOutputStream os = res.getOutputStream();
            yzmValue = GenerateCode.outputVerifyImage(110, 42,os,4);
            System.out.println(yzmValue);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return yzmValue;
    }

    @Override
    public SUser loginIn(SUser theUser) {
        System.out.println(theUser.getUsername()+"--"+theUser.getPassword());
        SUser ResultUser = JdbcUtils.selectOne(SUser.class,
                "select * from s_user where username=? and password=?"
                , theUser.getUsername(), MdsUtils.encrpt(theUser.getPassword(),"user"));
        if (ResultUser!=null){
            System.out.println("登录成功!!");
            System.out.println("被登录的用户是:"+ResultUser.toString());
            return ResultUser;
        }else {
            System.out.println("登录失败!!");
        }
        return null;
    }

    @Override
    public int update(SUser user) {
        return JdbcUtils.update("update s_user set username=?,password=?,type=?,userimg=? where id=?",user.getUsername(),user.getPassword(),user.getType(),user.getUserimg(),user.getId());
    }

    //通过id查询用户
    public SUser queryOne(String id){
        return JdbcUtils.selectOne(SUser.class,"select * from s_user where id=?",id);
    }

    //用户添加
    @Override
    public void insert(SUser user) {
        JdbcUtils.update("insert into s_user(id,username,password,type,userimg) values(?,?,?,?,?)",
                user.getId(),user.getUsername(),MdsUtils.encrpt(user.getPassword(),"user"),user.getType(),user.getUserimg());

    }

    ////通过id删除用户
    @Override
    public void deleteUser(String id) {
        JdbcUtils.update("delete from s_user where id=?", id);
    }

}
